﻿package com.nicoB.tetris {
	import com.nicoB.tetris.events.TetrisEvent;	
	import com.nicoB.tetris.blocks.BlockItem;
	
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;		

	/**
	 * @author n.bush
	 * @project tetris
	 * @date 5 nov. 2008
	 * @desc 
	 */
	public class Renderer extends Sprite {
		
		private var _cellWidth : Number;
		private var _cells : Array;
		private var _timerRemoveLines : Timer;

		private var _isRemovingLines : Boolean;
		
		
		public function Renderer(cellWidth : Number) {
			_cellWidth = cellWidth;
			
			_timerRemoveLines = new Timer(5 / 30 * 1000, 1);
			_timerRemoveLines.addEventListener(TimerEvent.TIMER_COMPLETE, _onTimeOut, false, 0, true);
		}
		
		public function draw(cells : Array):void{
		
			if (_isRemovingLines)
				return;
		
			_clear();
			
			_cells = [];
			
			for (var i : uint = 0; i < cells.length; i++) {
				
				var line : Array = [];
				
				for (var j : uint = 0; j < cells[i].length; j++) {
					if (cells[i][j] != 0){
						line.push(_drawCell(j, i, cells[i][j]));
					}
					else {
						line.push(null);
					}
				}
				
				_cells.push(line);
			}
			
		}
		
		
		
		
		private function _drawCell(line : uint, col : uint, color : uint) : BlockItem {
			
			var block : BlockItem = new BlockItem();
			block.x = line * _cellWidth;
			block.y = col * _cellWidth;
			block.color = color;
			addChild(block);
			
			return block;
		}
		
		
		private function _clear():void{
			while (numChildren > 0){
				var block : BlockItem = getChildAt(0) as BlockItem;
				removeChild(block);
				block = null;
			}
			
			_cells = null;
		} 

		
		public function removeLines(lines : Array) : void {
			
			_isRemovingLines = true;
			
			for (var i : Number = 0; i < lines.length; i++) {
				for (var j : Number = 1; j < _cells[lines[i]].length-1; j++) {
					(_cells[lines[i]][j] as BlockItem).disappear();
				}
			}
			
			_timerRemoveLines.reset();
			_timerRemoveLines.start();
		}

		
		private function _onTimeOut(e : TimerEvent) : void {
			var e2 : TetrisEvent = new TetrisEvent(TetrisEvent.LINES_REMOVED);
			dispatchEvent(e2);
			
			_timerRemoveLines.stop();
			
			_isRemovingLines = false;
			
		}
	}
}
